package com.gsafety.wellsfort.common.util;


import com.alibaba.fastjson.JSON;
import com.gsafety.wellsfort.common.enums.StatusEnum;
import com.gsafety.wellsfort.domain.PageQuery;
import com.gsafety.wellsfort.domain.vo.QueryVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * 通用参数工具类构建
 *
 * @author tangjiawei
 */
@Slf4j
public class MapUtils {
    /**
     * 构建查询参数
     *
     * @param t
     * @param <T>
     * @return
     */
    public static <T extends QueryVO> Map<String, Object> buildQueryParam(T t) {
        QueryVO query = (QueryVO) t;
        return buildQueryParam(query, t);
    }

    /**
     * 通过请求查询构建
     *
     * @param query
     * @param t
     * @param <T>
     * @return
     */
    public static <T> Map<String, Object> buildQueryParam(QueryVO query, T t) {
        Map<String, Object> map = new HashMap<>(16);
        //设置startIndex
        map.put(PageQuery.KEY_START_INDEX, query.getStartIndex());
        map.put(PageQuery.KEY_PAGE_SIZE, query.getPageSize());
        if (StringUtils.isNotEmpty(query.getOrderBy()) && (PageQuery.DIRECTION_ASC.equalsIgnoreCase(query.getSortType()) || PageQuery.DIRECTION_DESC.equalsIgnoreCase(query.getSortType()))) {
            map.put(PageQuery.KEY_ORDER_BY, query.getOrderBy());
            map.put(PageQuery.KEY_SORT_TYPE, query.getSortType());
        }
        if (t != null) {
            try {
                Class<?> cls = t.getClass();
                Field[] fields = cls.getDeclaredFields();
                for (Field field : fields) {
                    field.setAccessible(true);
                    if (field.get(t) != null) {
                        map.put(field.getName(), field.get(t));
                    }
                }
            } catch (IllegalAccessException e) {
                log.error("exception", e);
            }
        }
        log.info("请求查询参数,query={}", JSON.toJSON(map));
        return map;
    }

}
